var mongoose = require('mongoose'),
	glob = require('glob'),
	path = require('path'),
	_ = require('lodash');
var mongodbConf = require('../config/mongodb.json');
var db = mongoose.connection,lastTime;

  db.on('connecting', function() {
    console.log('connecting to MongoDB...');
  });

  db.on('error', function(error) {
    console.error('Error in MongoDb connection: ' + error);
    mongoose.disconnect();
  });
  db.on('connected', function() {
    console.log('MongoDB connected!');
  });
  db.once('open', function() {
    console.log('MongoDB connection opened!');
  });
  db.on('reconnected', function () {
    console.log('MongoDB reconnected!');
  });
  db.on('disconnected', function() {
    console.log('MongoDB disconnected!');
    var nowTime = new Date().getTime();
    if(!lastTime || nowTime - lastTime < 5000){
    	
    	var delay = 5000 - (nowTime - lastTime);
    	
    	console.log('.............................................'+delay);
    	setTimeout(function(){
    		lastTime = new Date().getTime();
			mongoose.connect(mongodbConf.url, {server:{auto_reconnect:true}});
    	},delay)
    }else{
    	console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
    	lastTime = nowTime;
    	mongoose.connect(mongodbConf.url, {server:{auto_reconnect:true}});
    }
    
  });
  mongoose.connect(mongodbConf.url,{
	server: {
		auto_reconnect: true,
		poolSize: 5,
	}
	,
	replset: {
		
	//	rs_name: 'cloud-rs'
	}
});

// db.on('error',function(err){
// 	console.error('链接mongodb失败'+mongodbConf.url);
// 	console.error(err);
// });

// db.on('connected',function(err){
// 	if(err){
// 		console.error('连接失败');
// 	}
// 	console.error('连接。。。。。。。。。。。。。');
// });

// mongoose.connection.on('',function(){

// });


var modelFiles = glob.sync("./**/*.model.js");
_.forEach(modelFiles,function(mf){
	require(path.resolve(mf));
});